<?php
$loader->requireOnce('ordo/Service.class.php');

class SurgeryService extends ORDataObject{
	var $service_id			=	'';
	var $enum_surgery_type	=	'';
	var $surgery_service_group_id		=	'';
	var $surgery_service_allowance_id	=	'';
	
	var $_table				=	'surgery_service';
	var $_key				=	'service_id';
	var	$_internalName		=	'SurgeryService';
	var $_foreignKeyList	=	array(
		'service_id'	=>	'service',
		'surgery_service_group_id'		=> 'surgery_service_group',
		'surgery_service_allowance_id'	=> 'surgery_service_allowance'
	);
	
	var $service	=	'';
	
	const SUR_TYPE_SMALL	=	'small';
	const SUR_TYPE_MEDIUM	=	'medium';
	const SUR_TYPE_BIG		=	'big';
	
	public function SurgeryService(){
		parent::ORDataObject();
	}
	
	public function setup($id = 0){
		$this->set('id',$id);
		if($id>0){
			$this->populate();
			$this->service	=	Celini::newORDO('Service',$id);
		}
	}
	
	public function populate(){
		parent::populate('service_id');
	}
	
	/*public function setData($service_id, $surgery_type){
		$data = array(	
			'service_id'  	=> $service_id,
			'surgery_type'	=> $surgery_type
		);
		$this->populateArray($data);
	}
	
	public function setData($service_id, $surgery_type, $surgery_class){
		$data = array(	
			'service_id'  	=> $service_id,
			'surgery_type'	=> $surgery_type,
			'enum_allowance_class'	=> $surgery_class
		);
		$this->populateArray($data);
	}*/

	public function getId(){
		return $this->service_id;
	}
	
	public function setId($id){
		$this->service_id=$id;
	}
	public function getSurgeryNameById($servId){
		$this->service	=	Celini::newORDO('Service',$servId);
		return $this->service->getLocalizedText('name');
	}
	
	public static function getSurgeryTypeList(){
		$list	=	array(
    		self::SUR_TYPE_SMALL	=> 	L10nHelper::_("Small surgery"),
    		self::SUR_TYPE_MEDIUM	=>	L10nHelper::_("Medium sugery"),
    		self::SUR_TYPE_BIG		=>	L10nHelper::_("Big surgery"));
        return $list;
	}
	
	public function getSurgeryType(){
		return $this->surgery_type;
	}
	
	public function getSurgeryTypeText(){
		$list	=	self::getSurgeryTypeList();
		if(!array_key_exists($this->type, $list)){
			return '';
		}
		return $list[$this->type];
	}
	
	public function getServiceObject(){
		return $this->service;
	}
	
	public static function getServiceList($recordId,$justName = false){
	    $field        =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
		
		$obj	=	Celini::newORDO('SurgeryService');
		$ds		=	& new Datasource_sql();
		$objRe	=	Celini::newORDO('MedicalRecord');
		$objRe->setUp($recordId);
		$ticketId = $objRe->get('ticket_id');
		
		$sql	=	array(
			'cols'	=>	"a.service_id as id, b.$field as name, a.surgery_type as type, b.price",
			'from'	=> 	"ticket t INNER JOIN ticket_item ti ON (t.ticket_id=ti.ticket_id AND t.ticket_id=$ticketId) " .
					" INNER JOIN $obj->_table a ON a.service_id=ti.item_id
					INNER JOIN service b ON a.service_id=b.service_id"			
		);
		
		$ds->setup($obj->_db, $sql);	
		return $ds->toArray();		
	}
	
	public function getServiceInfo($deptId, $disabled, $type) {
	    $fieldName        =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
	    $fieldTitle        =   L10nHelper::changeField(L10nHelper::getLocale(), 'title');

        $enumGroupId =	Utils::getEnumGroupName(EnumerationConstant::SURGERY_SERVICE_ALLOWANCE_CLASS);
        $enumValTbl	=	ORDataObject::factory('EnumerationValue')->tableName();
		
		$ds = new Datasource_sql();
		$sql = array (
			'cols'	=> "a.service_id, b.$fieldName name, 
				b.price, b.required_insurance_price, b.volunteered_insurance_price,
				b.patient_required_insurance_price, b.patient_volunteered_insurance_price,
				b.payment_type, b.disabled, a.surgery_type, e.$fieldTitle allowance_class",
			'from'		=> "$this->_table a LEFT JOIN ".$this->_foreignKeyList['service_id']." b 
				ON a.service_id=b.service_id				
                LEFT JOIN $enumValTbl e ON (a.enum_allowance_class=e.key AND e.enumeration_id=$enumGroupId) ",
			'where'		=> "b.item_type='service'",
			'orderby'	=> "disabled, name"
			);
		if ($deptId !== false) {
			$sql['where'] .= " AND b.department_id = $deptId"; 	
		}
		
		if ($disabled !== false) {
			$sql['where'] .= " AND b.disabled = $disabled";
		}
		
		if ($type) {
			$sql['where'] .= " AND a.surgery_type = '$type'";
		}
		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}
	
    public function getInServiceInfo($deptId, $disabled, $surgeryType, $surgeryClassify) {
        $field =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');        
        
        $ds = new Datasource_sql();
        $sql = array (
            'cols'  => "a.service_id, b.$field name, 
                b.price, b.required_insurance_price, b.volunteered_insurance_price,
                b.patient_required_insurance_price, b.patient_volunteered_insurance_price,
                b.payment_type, b.disabled, a.surgery_type",
            'from'      => "$this->_table a 
                            LEFT JOIN ".$this->_foreignKeyList['service_id']." b 
                                ON a.service_id=b.service_id",
            'where'     => "b.item_type='service'",
            'orderby'   => "name"
            );
        if ($deptId !== false) {
            $sql['where'] .= " AND b.department_id = '$deptId'";  
        }
        
        if ($disabled !== false) {
            $sql['where'] .= " AND b.disabled = $disabled";
        }
        
        if ($surgeryType) {
            $sql['where'] .= " AND a.surgery_type = '$type'";
        }
        
        if ($surgeryClassify) {
            $sql['where'] .= " AND a.enum_surgery_classify = '$surgeryClassify'";
        }
        $ds->setup($this->_db, $sql);
        return $ds->toArray();
    }
    
    /**
     * List all available surgery services in catergory and sub group view
     * @param $groupId: sub group id
     * @return array('service_id' => id, 'name' => name, 'allowance_class' => allowance class, 'allowance' => allowance
     */
    public function listSurgeryServicesInGroupView($groupId){
        $fieldName        =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');    	
        
        $ds		= new Datasource_sql();
        $sql	= array(
        	'cols'		=>	"sur.service_id, ser.$field name, alwc.enum_allowance_class allowance_class, 
        					alwc.allowance",
        	'from'		=>	"$this->_table sur 
        					LEFT JOIN ".$this->_foreignKeyList['service_id']." ser ON sur.service_id = ser.service_id         					         					
        					LEFT JOIN ".$this->_foreignKeyList['surgery_service_allowance_id']." alwc 
        						ON sur.surgery_service_allowance_id = alwc.surgery_service_allowance_id",
        	'where'		=>	"ser.disabled=0",
        	'orderby'	=>	'alwc.enum_allowance_class, alwc.allowance'
        );
        if($groupId !== NULL){
        	$sql['where'] .= " AND sur.surgery_service_group_id=$groupId";
        }
        $ds->setup($this->_db, $sql);
        return $ds->toArray();
    }
    
    /**
     * List all available surgery services in type of surgery view
     * @param $type: type of surgery (major, minor,..)
     * @return array('service_id' => id, 'name' => name, 'type' => type)
     */
    public function listSurgeryServicesInTypeView($type='all'){        
    	$field      =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');        
        
        $ds		= new Datasource_sql();
        $sql	= array(
        	'cols'		=>	"sur.service_id, ser.$field name, sur.enum_surgery_type type",
        	'from'		=>	"$this->_table sur 
        	       LEFT JOIN " . $this->_foreignKeyList['service_id'] . " ser 
        	           ON sur.service_id = ser.service_id ",
        	'where'		=>	"ser.disabled=0",
        	'orderby'	=>	'name'
        );
        if($type!=='all'){
        	$sql['where']	.=	" AND sur.enum_surgery_type=$type";
        }
        $ds->setup($this->_db, $sql);
        return $ds->toArray();
    }
    
    public function listAllSurgeryService(){
        $field      =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
    	
        $ds		= new Datasource_sql();
        $sql	= array(
        	'cols'		=>	"sur.service_id, ser.$field name, sur.surgery_service_group_id group_id, "
        					."sur.enum_surgery_type type",
        	'from'		=>	"$this->_table sur LEFT JOIN ".$this->_foreignKeyList['service_id']." ser "
        					."ON sur.service_id = ser.service_id ",
        	'where'		=>	"ser.disabled=0",
        	'orderby'	=>	'name'
        );
        $ds->setup($this->_db, $sql);
        $result	=	$ds->toArray();
        $count	=	0;
        foreach($result as $item){
        	$typeName		=	Utils::getEnumTextByKey(EnumerationConstant::SURGERY_TYPE, $item['type']);
        	$item['type']	=	$typeName;
        	$result[$count]	=	$item;
        	$count++;
        }
        return $result;
    }
    
    /**
     * Edit the type of surgery service (major, minor...)
     * @param $servId: service id
     * @param $type: type of surgery
     */
    public function editSurgeryServiceType($servId, $type){
    	$this->setup($servId);
    	$this->set('enum_surgery_type', $type);
    	$this->persist();
    }
    
    /**
     * Edit the group which this sugery service belongs to, as well as its allowance class
     * @param $service: array(
     * 		'service_id'	=>	id,
     * 		'group_id'		=>	group id,
     * 		'allowance_class=>	allowance class id,
     * 		'allowance'		=>	enum allowance)
     */
    public function editSurgeryServiceGroup($service){
    	$this->setup($service['service_id']);
    	$this->set('surgery_service_group_id', $service['group_id']);
    	$allowance = Celini::newORDO('SurgeryServiceAllowance')->getAllowanceId($service['allowance_class'], $service['allowance']);
    	$this->set('surgery_service_allowance_id', $allowance['allowance_id']);
    	$this->persist();
    }
    
    /**
     * Save new service to surgery service table
     * @param $service: array(
     * 		'service_id'	=>	id,
     * 		'group_id'		=>	group id,
     * 		'type'			=>	enum surgery type,
     * 		'allowance_class=>	allowance class id,
     * 		'allowance'		=>	enum allowance)
     */    
    public function saveNewSurgeryService($service){
    	$this->setup($service['service_id']);
    	$this->set('surgery_service_group_id', $service['group_id']);
    	$this->set('enum_surgery_type', $service['type']);
    	$allowance = Celini::newORDO('SurgeryServiceAllowance')->getAllowanceId($service['allowance_class'], $service['allowance']);
    	$this->set('surgery_service_allowance_id', $allowance['allowance_id']);
    	$this->persist();
    }
    
	/**
	 * Prepare data for redering 'Select Surgery Service' pop up 
	 * In order to render the pop up correctly, should assign 'groupList' and 'servList' to viewer
	 * @return array('groupList' => list of all sugery groups, 'servList' => list of all surgery services) 
	 */
	public function getData4RenderSelectSurgeryService(){
		$catergories	=	Celini::newORDO('SurgeryServiceGroup')->listSurgeryServiceGroup();
		$groupList		=	array();
		$count		=	0;
		foreach($catergories as $catergory){
			$group = Celini::newORDO('SurgeryServiceGroup')->listSurgeryServiceGroup($catergory['group_id']);
			$groupList[$count]	=	array(
				'parent_id'		=>	$catergory['group_id'],
				'parent_name'	=>	$catergory['group_name'],
				'groups'		=>	$group
			);
			$count++;
		}
		$result	=	array(
			'groupList'	=>	$groupList,
			'servList'	=>	$this->listAllSurgeryService()
		);
		return $result;
	}
}
?>